package com.hooya.fa.eu.biz.dao.manager.special;

import com.hooya.fa.eu.api.bo.LastCostBO;
import com.hooya.fa.eu.api.bo.MetaStkCustomsBO;
import com.hooya.fa.eu.api.bo.TradeRecordBO;
import com.hooya.fa.eu.api.bo.TradeRecordHisBO;
import com.hooya.fa.eu.api.enums.CountryEnum;
import com.hooya.fa.eu.api.enums.OtherCompanyEnum;
import com.hooya.fa.eu.api.util.MD5Util;
import com.hooya.fa.eu.biz.dao.entity.StkOriginCollect;
import com.hooya.fa.eu.biz.dao.entity.TradeRecord;
import com.hooya.fa.eu.biz.dao.mapper.MetaRelationMapper;
import com.hooya.integrated.common.core.util.BeanCopyUtils;
import com.hooya.integrated.common.util.times.DateExtUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 1
 * @Author : Zongz
 * @Copyright Copyright (c) 豪雅集团
 * @Create 2023/12/1
 * @Version 1.0.0
 */
@Slf4j
@Component
@AllArgsConstructor
public class TradeRecordB2bManager {

    private final MetaRelationMapper metaRelationMapper;

    /**
     * 取出买卖记录中不存在买卖记录（含价格和海运费）的产品编号的买卖记录数据（差值数据）
     *
     * @param historyList 买卖记录（含价格和海运费）
     * @param hisMap      所有历史价格
     * @param recordList  在时间范围内，最早买卖记录
     */
    public void getHisDifferentialData(List<TradeRecordHisBO> historyList, Map<String, LastCostBO> hisMap,
                                       List<TradeRecord> recordList) {
        // 将historyList的产品编号去重，为后续取差值数据做准备
        List<TradeRecordHisBO> distinctRecordList = historyList.stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(TradeRecordHisBO::getCpbh))), ArrayList::new));
        Map<String, TradeRecordHisBO> recordHisMap = distinctRecordList.stream()
                .collect(Collectors.toMap(TradeRecordHisBO::getCpbh, i -> i));
        //准备差值数据,并合并
        recordList.forEach(l -> {
            if (Objects.isNull(recordHisMap.get(l.getCpbh()))) {
                TradeRecordHisBO bo = new TradeRecordHisBO();
                bo.setCpbh(l.getCpbh());
                LastCostBO cost = hisMap.get(l.getCpbh());
                if (Objects.nonNull(cost)) {
                    bo.setPrice(cost.getLastPrice());
                    bo.setOceanFee(cost.getOceanFee());
                } else {
                    log.info("最新数据没有产品编号为：【" + l.getCpbh() + "】的数据");
                }
                //合并差值数据
                historyList.add(bo);
            }
        });
    }


    /**
     * 设置买家卖家（有些公司有税号后，逻辑会改动）
     *
     * @param recordBoList 买卖记录
     */
    public void setBuyerSeller(List<TradeRecordBO> recordBoList) {
        recordBoList.stream().map(l -> {
            //卖家与买家（normal）
            l.setStax(l.getFromCountry());
            l.setBtax(l.getToCountry());
            //其他买家(买家税号：收货地除DE，PL，IT，ES外均使用FR/无ES税号的四家公司，改为FR) # lifezeal去掉
            if (!Arrays.asList("DE", "PL", "IT", "ES").contains(l.getToCountry()) ||
                    (Arrays.asList("komfort", "giantex", "kerui").contains(l.getTocompany())
                            && l.getToCountry().equals("ES"))) {
                l.setBtax(CountryEnum.FR.getCountry());
            }
            /**
             * 特殊买家
             */
            //买家为法国，公司是keerxi 或者 买家为波兰，公司是kerui 2023.12月开始失效
//            if ((CountryEnum.FR.getCountry().equals(l.getBtax()) && OtherCompanyEnum.KEERXI.getCompany().equals(l.getTocompany())) ||
//                    (CountryEnum.PL.getCountry().equals(l.getBtax()) && OtherCompanyEnum.KERUI.getCompany().equals(l.getTocompany()))) {
//                //只有卖家是德国是买家是IT，其他卖家（FR，IT，PL）的买家都是DE
//                if (CountryEnum.DE.getCountry().equals(l.getFromCountry())) {
//                    l.setBtax(CountryEnum.IT.getCountry());
//                } else {
//                    l.setBtax(CountryEnum.DE.getCountry());
//                }
//            }
            if (OtherCompanyEnum.MINGDUN.getCompany().equals(l.getTocompany())) {
                l.setBtax(CountryEnum.FR.getCountry());
            }
            if (OtherCompanyEnum.ITSRLCOSTWAY.getCompany().equals(l.getTocompany())) {
                l.setBtax(CountryEnum.IT.getCountry());
            }

            //买家公司为kerui，并且卖家税号为PL
            if (CountryEnum.PL.getCountry().equals(l.getBtax()) &&
                    l.getTocompany().equals(OtherCompanyEnum.KERUI.getCompany())) {
                //卖家国家为DE
                if (CountryEnum.DE.getCountry().equals(l.getFromCountry())) {
                    l.setBtax(CountryEnum.IT.getCountry());
                }
                //卖家国家为FR、IT、PL
                if (CountryEnum.FR.getCountry().equals(l.getFromCountry()) ||
                        CountryEnum.IT.getCountry().equals(l.getFromCountry()) ||
                        CountryEnum.PL.getCountry().equals(l.getFromCountry())) {
                    l.setBtax(CountryEnum.FR.getCountry());
                }
            }
            return l;
        }).collect(Collectors.toList());
    }

    /**
     * 填充主数据内容，并最后生成拆分成两份（进口与出口）
     *
     * @param recordBoList 主数据
     * @param startDate    开始时间（获取数据）
     * @param historyList  金额数据
     */
    public List<StkOriginCollect> fillB2BData(List<TradeRecordBO> recordBoList, String startDate,
                                              List<TradeRecordHisBO> historyList) {
        //最终结果
        List<StkOriginCollect> res = new LinkedList<>();
        List<String> corpHeader = metaRelationMapper.getCorpHeaderByCountry();
        //发票相关时间
        String curMonthLastDay = DateExtUtil.getCurMonthLastDay(null);
        String nextMonthFirstDay = DateExtUtil.getNextMonthFirstDay(null, 1);
        //获取关税
        List<MetaStkCustomsBO> metaStkCustomsBOList = metaRelationMapper.getListByCondition(curMonthLastDay);
        Map<String, Long> stkCustomsSizeMap = metaStkCustomsBOList.stream()
                .collect(Collectors.groupingBy(l -> l.getSku() + l.getBelongs(), Collectors.counting()));
        Map<String, List<MetaStkCustomsBO>> stkCustomsBoMap = metaStkCustomsBOList.stream()
                .collect(Collectors.groupingBy(MetaStkCustomsBO::getSku));
        //historyList
        Map<String, TradeRecordHisBO> hisPriceMap = historyList.stream().collect(Collectors.toMap(TradeRecordHisBO::getCpbh, i -> i));
        recordBoList.forEach(l -> {
            //-------通用数据id，invoiceDate，出口价格，外销价格，海运费-------
            //md5加密字段生成
            String idStr = startDate + l.getFromcompany() + l.getTocompany() + l.getFromCountry() + l.getStax() + l.getBtax();
            l.setId(MD5Util.sec4md5(idStr));
            if (corpHeader.contains(l.getTocompany().split("-")[0])) {
                l.setInvoiceDate(nextMonthFirstDay);
            } else {
                l.setInvoiceDate(curMonthLastDay);
            }
            Long size = stkCustomsSizeMap.get(l.getCpbh() + l.getAbbrbelongs());
            if (Objects.isNull(size)) {
                //该产品编号，没有该货权地，所以数据应该只会有一条
                List<MetaStkCustomsBO> onlyOne = stkCustomsBoMap.get(l.getCpbh());
                l.setExportPrice(onlyOne.get(0).getPrice());
            } else {
                //通常情况下，根据产品编号取，会有2条货权
                if (CollectionUtils.isEmpty(stkCustomsBoMap.get(l.getCpbh()))) {
                    log.info("产品编号为：【" + l.getCpbh() + "】无出口价格");
                } else {
                    List<MetaStkCustomsBO> twoDataCustoms = stkCustomsBoMap.get(l.getCpbh())
                            .stream().filter(c -> c.getBelongs().equals(l.getAbbrbelongs())).collect(Collectors.toList());
                    l.setExportPrice(twoDataCustoms.get(0).getPrice());
                }
            }
            //合并数据 historyList 与 recordBoList
            TradeRecordHisBO bo = hisPriceMap.get(l.getCpbh());
            if (Objects.nonNull(bo)) {
                l.setPrice(bo.getPrice());
                l.setOceanFee(bo.getOceanFee());
            }
            //进口数据设置
            l.setBelongs(l.getTocompany());
            l.setDirection("in");
            StkOriginCollect inData = BeanCopyUtils.turnToVO(l, StkOriginCollect.class);

            //出口数据生成
            StkOriginCollect outDate = BeanCopyUtils.copyPropertiesNew(inData, StkOriginCollect::new);
            outDate.setBelongs(l.getFromcompany());
            outDate.setDirection("out");

            res.add(inData);
            res.add(outDate);
        });
        return res;
    }

    /**
     * 修改tocampany的fds、costway拼接为处理后的买家税号 其他不变
     *
     * @param recordBoList 买卖记录列表
     */
    public void resolveTocompany(List<TradeRecordBO> recordBoList) {
        for (TradeRecordBO record : recordBoList) {
            String toCompany = record.getTocompany();
            //处理后的买方税号
            String buyerTaxId = record.getBtax().toLowerCase();
            if ("fds".equals(toCompany)) {
                record.setTocompany("fds-".concat(buyerTaxId));
            } else if ("costway".equals(toCompany)) {
                record.setTocompany("costway-".concat(buyerTaxId));
            }
        }
    }
}
